package geo.campus;

import java.io.InputStream;
import java.util.ArrayList;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;

public class PopUp {

	private double lonarr;
	private double latarr;
	private String addrarr = "";
	private String nomarr = "";

	private TextView nombat;
	private TextView addrbat;
	private TextView numtelbat;
	private ImageView photo;
	private EditText etarr;
	private Spinner zone;
	private Spinner cat;
	private Spinner nom;
	private Spinner campus;
	private Button valider;
	private Button itipu;
	private Button navpu;
	private Button annuler;
	private Button annulerres;
	private Button nouvellerec;
	private Button affichecarte;
	private Button aller;
	private RadioButton rbpieton;
	private RadioButton rbvoiture;

	private ArrayAdapter<String> adapt;
	private ArrayAdapter<String> adapt1;
	private ArrayAdapter<String> adapt2;
	private ArrayAdapter<CharSequence> adapt3;

	private boolean iti = false;
	private boolean parcoursfixe;
	private boolean pieton;
	private boolean fini = false;
	private boolean finires = false;

	private Context act;

	private Dialog dialogrec;
	private Dialog mdialog;
	private Dialog dialogres;

	private DatabaseAdaptateur mabd;

	private boolean selectcat = false;
	private boolean selectzone = false;

	private InputStream is;

	/** Called when the activity is first created. 
	 * @param itemizedoverlay 
	 * @param mapView */
	public PopUp(Context ctx)
	{

		act = ctx;
		adapt = new ArrayAdapter<String>(act, android.R.layout.simple_spinner_item);
		adapt1 = new ArrayAdapter<String>(act, android.R.layout.simple_spinner_item);
		adapt2 = new ArrayAdapter<String>(act, android.R.layout.simple_spinner_item);
		adapt3 = ArrayAdapter.createFromResource(act, R.array.campus, android.R.layout.simple_spinner_item);

		adapt3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		this.mabd = new DatabaseAdaptateur(act);


		dialogrec = new Dialog(act);
		dialogrec.setContentView(R.layout.recherche);

		valider = (Button) dialogrec.findViewById(R.id.btrecherche);
		campus = (Spinner) dialogrec.findViewById(R.id.campus);
		campus.setAdapter(adapt3);
		zone = (Spinner) dialogrec.findViewById(R.id.zone);
		cat = (Spinner) dialogrec.findViewById(R.id.categorie);
		nom = (Spinner) dialogrec.findViewById(R.id.nombat);

		mdialog = new Dialog(act);

		mdialog.setContentView(R.layout.itinerairepopup);
		mdialog.setTitle("Itinéraire");


		itipu = (Button) mdialog.findViewById(R.id.ButtonItineraire);
		navpu = (Button) mdialog.findViewById(R.id.ButtonNavigation);
		annuler = (Button) mdialog.findViewById(R.id.ButtonAnnuler);

		etarr = (EditText) mdialog.findViewById(R.id.autocomplete_country);
		rbpieton = (RadioButton) mdialog.findViewById(R.id.RadioButtonPieton);
		rbvoiture = (RadioButton) mdialog.findViewById(R.id.RadioButtonVoiture);

		dialogres = new Dialog(act);
		dialogres.setContentView(R.layout.resultat);
		dialogres.setTitle("Résultat");

		photo = (ImageView) dialogres.findViewById(R.id.image2);
		nombat = (TextView) dialogres.findViewById(R.id.nombatres);
		addrbat = (TextView) dialogres.findViewById(R.id.addrbatres);
		numtelbat = (TextView) dialogres.findViewById(R.id.numbatres);
		aller = (Button) dialogres.findViewById(R.id.btfaireitiendir);
		affichecarte = (Button) dialogres.findViewById(R.id.btvalrec);
		nouvellerec = (Button) dialogres.findViewById(R.id.btnouvellerec);
		annulerres = (Button) dialogres.findViewById(R.id.btannuler);
	}


	public void dialres()
	{
		mabd.open();
		Cursor c = mabd.selectinfores(nomarr);
		if(c.getCount() != 0)
		{
			c.moveToFirst();
			numtelbat.setText(c.getString(0));
			nombat.setText(nomarr);
			addrbat.setText(addrarr);
			String photo1 = c.getString(1);
			if(photo1 != null)
			{
				java.lang.reflect.Field field;
				try {
					field = R.drawable.class.getField(photo1);
					int id = field.getInt(R.drawable.class);

					photo.setImageResource(id);
				} catch (SecurityException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (NoSuchFieldException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else
			{
				photo.setImageResource(R.drawable.btn_close_selected);
			}
			c.close();
			mabd.close();
		}

		annulerres.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogres.cancel();
			}
		});

		nouvellerec.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogres.cancel();
				recdialog(false);
			}
		});

		aller.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogres.cancel();
				dialog(true, false);
			}
		});

		affichecarte.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialogres.cancel();
				setFinires(true);
			}
		});

		dialogres.show();
	}


	public void alertdial()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setMessage("Entrer une destination")
		.setCancelable(false)
		.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}


	public void dialog(boolean arrivee, boolean depart)
	{

		etarr.setText(null);
		if(arrivee && addrarr != "null")
		{
			etarr.setText(nomarr + ", " + addrarr);
		}
		else
			if(arrivee)
				etarr.setText(nomarr);

		etarr.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				recdialog(true);
				mdialog.cancel();
			}
		});

		itipu.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(nomarr.length() == 0)
				{
					alertdial();
				}
				else
				{
					if(rbpieton.isChecked())
					{
						mdialog.cancel();
						setPieton(true);
						setParcoursfixe(true);
						setFini(true);
					}
					else
					{
						mdialog.cancel();
						setPieton(false);
						setParcoursfixe(true);
						setFini(true);
					}
				}
			}
		});

		navpu.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(nomarr.length() == 0)
				{
					alertdial();
				}
				else
				{
					if(rbvoiture.isChecked())
					{
						mdialog.cancel();
						setParcoursfixe(false);
						String mlocation = Double.toString(latarr)+","+Double.toString(lonarr);
						Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q="+ mlocation));
						act.startActivity(i);
						setFini(true);
					}
					else
					{
						mdialog.cancel();
						setParcoursfixe(false);
						String mlocation = Double.toString(latarr)+","+Double.toString(lonarr);
						Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q="+ mlocation+ "&mode=w"));
						act.startActivity(i);
						setFini(true);
					}
				}
			}
		});

		annuler.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				mdialog.cancel();
			}
		});
		mdialog.show();
	}

	public void recdialog(boolean it)
	{
		mabd.open();
		iti = it;

		remplirspinnernom(0);
		remplirspinnercat(0);
		remplirspinnerzone(0);

		if(iti)
			dialogrec.setTitle("Selection Batiment");
		else
			dialogrec.setTitle("Recherche");
		Button annuler1 = (Button) dialogrec.findViewById(R.id.btrechercheann);

		annuler1.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialogrec.cancel();
				mabd.close();
			}
		});

		zone.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg2 == 0)
				{
					selectzone = false;
				}
				else
				{

					if(selectcat)
					{
						Cursor c = mabd.selectbycatandid(cat.getSelectedItem().toString(), zone.getSelectedItem().toString());
						if(c.getCount() !=0)
						{
							c.moveToFirst();
							String[] res1 = new String[c.getCount()+1];
							int i = 0;
							res1[i] = "--Nom";
							do
							{
								i++;
								res1[i] = c.getString(0);
							}
							while(c.moveToNext());
							modifspinner(res1);
							c.close();
						}
						else
						{
							String[] res1 = new String[1];
							res1[0] = "--Nom";
							modifspinner(res1);
						}
					}
					else
					{
						String z = zone.getSelectedItem().toString();
						Cursor c = mabd.selectbyzone(z);
						if(c.getCount() !=0)
						{
							c.moveToFirst();
							String[] res1 = new String[c.getCount()+1];
							int i = 0;
							res1[i] = "--Nom";
							do
							{
								i++;
								res1[i] = c.getString(0);
							}
							while(c.moveToNext());
							modifspinner(res1);
							c.close();
							selectzone = true;
						}
						else
						{
							String[] res1 = new String[1];
							res1[0] = "--Nom";
							modifspinner(res1);
							selectzone = true;
						}
					}
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});


		cat.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub

				if(arg2 == 0)
				{
					selectcat = false;
				}
				else
				{
					if(selectzone)
					{
						Cursor c = mabd.selectbycatandid(cat.getSelectedItem().toString(), zone.getSelectedItem().toString());
						if(c.getCount() !=0)
						{
							c.moveToFirst();
							String[] res1 = new String[c.getCount()+1];
							int i = 0;
							res1[i] = "--Nom";
							do
							{
								i++;
								res1[i] = c.getString(0);
							}
							while(c.moveToNext());
							modifspinner(res1);
							c.close();
						}
						else
						{
							String[] res1 = new String[1];
							res1[0] = "--Nom";
							modifspinner(res1);
						}
					}
					else
					{
						Cursor c = mabd.selectbycat(cat.getSelectedItem().toString());
						if(c.getCount() !=0)
						{
							c.moveToFirst();
							String[] res1 = new String[c.getCount()+1];
							int i = 0;
							res1[i] = "--Nom";
							do
							{
								i++;
								res1[i] = c.getString(0);
							}
							while(c.moveToNext());
							modifspinner(res1);
							c.close();
							selectcat = true;
						}
						else
						{
							String[] res1 = new String[1];
							res1[0] = "--Nom";
							modifspinner(res1);
						}
					}
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		valider.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(nom.getSelectedItem().toString() != "--Nom")
				{
					Cursor res = mabd.selectbynom(nom.getSelectedItem().toString());
					if(res.getCount() != 0)
					{
						res.moveToFirst();
						setNomarr(nom.getSelectedItem().toString());
						setAddrarr(res.getString(0));
						setLatarr(res.getDouble(1));
						setLonarr(res.getDouble(2));
					}
					if(iti)
					{
						dialogrec.cancel();
						dialog(true, false);
						mabd.close();
					}
					else
					{
						dialogrec.cancel();
						mabd.close();
						dialres();
					}
				}
				else
				{
					if(nom.getVisibility() == View.VISIBLE)
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(act);
						builder.setMessage("Selectionner un batiment")
						.setCancelable(false)
						.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

						AlertDialog alert = builder.create();
						alert.show();
					}
					else
					{
						AlertDialog.Builder builder1 = new AlertDialog.Builder(act);
						builder1.setMessage("Selectionner un campus")
						.setCancelable(false)
						.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

						AlertDialog alert1 = builder1.create();
						alert1.show();
					}
				} 

			}
		});

		campus.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg2 == 0)
				{
					zone.setVisibility(View.INVISIBLE);
					cat.setVisibility(View.INVISIBLE);
					nom.setVisibility(View.INVISIBLE);
					AlertDialog.Builder builder = new AlertDialog.Builder(act);
					builder.setMessage("Selectionner un campus")
					.setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});

					AlertDialog alert = builder.create();
					alert.show();
				}
				else
				{
					zone.setVisibility(View.VISIBLE);
					cat.setVisibility(View.VISIBLE);
					nom.setVisibility(View.VISIBLE);

					String lieu = campus.getSelectedItem().toString().toLowerCase();

					java.lang.reflect.Field field;
					try {
						field = R.raw.class.getField(lieu);
						int id = field.getInt(R.drawable.class);
						String[] statements = null;
						try{
							is = act.getResources().openRawResource(id);
							statements = FileHelper.parseSqlFile(is);

							for (String statement : statements) {
								mabd.insertsql(statement);
							}
							is.close();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					} catch (SecurityException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (NoSuchFieldException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					remplirspinnercat(1);
					remplirspinnernom(1);
					remplirspinnerzone(1);

				}
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		dialogrec.show();

	}

	private void remplirspinnernom(int id) 
	{
		// TODO Auto-generated method stub
		if(id==1)
		{
			Cursor c = mabd.selectallbat();

			String[] res = new String[c.getCount()+1];

			if(c.getCount() != 0)
			{
				c.moveToFirst();
				Integer i = 0;
				res[i] = "--Nom";
				do
				{
					i++;
					res[i] = c.getString(0);
				}
				while(c.moveToNext());
			}
			if(adapt.getCount() > 0)
			{
				adapt.clear();
			}
			for(int i = 0; i < res.length; i++)
				adapt.add(res[i]);
			c.close();
		}
		else
		{
			if(adapt.getCount() > 0)
			{
				adapt.clear();
			}
			adapt.add("--Nom");
		}
		adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		nom.setAdapter(adapt);

	}

	private void remplirspinnercat(int id)
	{
		if(id==1)
		{
			Cursor c1 = mabd.selectallcat();

			String[] res1 = new String[c1.getCount()+1];

			if(c1.getCount() != 0)
			{
				c1.moveToFirst();
				Integer i = 0;
				res1[i] = "--Categorie";
				do
				{
					i++;
					res1[i] = c1.getString(0);
				}
				while(c1.moveToNext());
			}
			if(adapt1.getCount() > 0)
			{
				adapt1.clear();
			}
			for(int i = 0; i < res1.length; i++)
				adapt1.add(res1[i]);
			c1.close();
		}
		else
		{
			if(adapt1.getCount() > 0)
			{
				adapt1.clear();
			}
			adapt1.add("--Categorie");
		}

		adapt1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		cat.setAdapter(adapt1);

	}

	private void remplirspinnerzone(int id)
	{
		if(id == 1)
		{
			Cursor c2 = mabd.selectallzone();

			String[] res2 = new String[c2.getCount()+1];

			if(c2.getCount() != 0)
			{
				c2.moveToFirst();
				Integer i = 0;
				res2[i] = "--Zone";
				do
				{
					i++;
					res2[i] = c2.getString(0);
				}
				while(c2.moveToNext());
			}
			if(adapt2.getCount() > 0)
			{
				adapt2.clear();
			}
			for(int i = 0; i < res2.length; i++)
				adapt2.add(res2[i]);
			c2.close();
		}
		else
		{
			if(adapt2.getCount() > 0)
			{
				adapt2.clear();
			}
			adapt2.add("--Zone");
		}
		adapt2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		zone.setAdapter(adapt2);

	}


	public InputStream getFic()
	{
		return is;
	}


	public void modifspinner(String[] res)
	{
		if(adapt.getCount() > 0)
		{
			adapt.clear();
		}

		for(String value : res)
		{
			adapt.add(value);
			// adapt.add(res[i1]);
		}

		adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		nom.setAdapter(adapt);
	}

	public ArrayList<OverlayItem> affiche_poi(String cat)
	{
		mabd.open();
		ArrayList<OverlayItem> al = new ArrayList<OverlayItem>();
		Cursor c = mabd.selectbycat2(cat);
		if(c.getCount() != 0)
		{
			c.moveToFirst();
			do
			{
				GeoPoint geoPoint = new GeoPoint((int)(c.getDouble(1)*1000000), (int)(c.getDouble(2)*1000000));
				OverlayItem overlayitem = new OverlayItem(geoPoint, c.getString(0), cat);
				al.add(overlayitem);
			}
			while(c.moveToNext());
		}
		c.close();
		mabd.close();
		return al;
	}


	public double getLonarr() {
		return lonarr;
	}

	public void setLonarr(double lonarr) {
		this.lonarr = lonarr;
	}

	public double getLatarr() {
		return latarr;
	}

	public void setLatarr(double latarr) {
		this.latarr = latarr;
	}

	public String getAddrarr() {
		return addrarr;
	}

	public void setAddrarr(String addrarr) {
		this.addrarr = addrarr;
	}

	public String getNomarr() {
		return nomarr;
	}

	public void setNomarr(String nomarr) {
		this.nomarr = nomarr;
	}

	public boolean isPieton() {
		return pieton;
	}

	public void setPieton(boolean pieton) {
		this.pieton = pieton;
	}

	public boolean isFini() {
		return fini;
	}

	public void setFini(boolean fini) {
		this.fini = fini;
	}

	public boolean isParcoursfixe() {
		return parcoursfixe;
	}

	public void setParcoursfixe(boolean parcoursfixe) {
		this.parcoursfixe = parcoursfixe;
	}


	public boolean isFinires() {
		return finires;
	}


	public void setFinires(boolean finires) {
		this.finires = finires;
	}

}
